<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/3
 * Time: 17:26
 */

namespace Admin\Model;
use Think\Model;
class CommentModel extends Model
{
    protected $tableName = "comment";
    protected $tablePrefix = "dangjian_";

    //查询所有评论
    public function queryAllComment ($data)
    {
        $name = $data['name'];//评论人姓名
        $time = $data['time'];//发布时间范围
        $is_show = $data['is_show'];//隐藏或显示
        $order = $data['order'];//排序字段
        $order1 = $data['order1'];//排序方式
        $map = array();
        if(!empty($name)){
            $map['u.name'] = array("LIKE", '%' . $name . '%');
        }
        if(!empty($time)){
            $start = substr($time,0,10);
            $end = substr($time,13,10);
            $start = date("Y-m-d H:i:s",strtotime($start));
            $end = date("Y-m-d H:i:s",strtotime($end));
            $map['c.create_time'] = array(array("gt",$start),array("lt",$end),"and");
        }
        if(!empty($is_show)){
            if($is_show == 2){
                $is_show = 0;
            }
            $map['c.is_show'] = $is_show;
        }

        if(empty($order)){
            $order = "c.id";
        }

        if(empty($order1)){
            $order1 = "asc";
        }

        $count = $this->alias("c")
            ->join("dangjian_user u on u.id = c.user_id")
            ->join("dangjian_communicate cc on c.article_id = cc.id")
            ->where($map)->count();
        $page = new \Think\Page($count,$this->showRow);
        $show = $page -> show();

        $list = $this->alias("c")
            ->join("dangjian_user u on u.id = c.user_id")
            ->join("dangjian_communicate cc on c.article_id = cc.id")
            ->field("c.id, u.name, cc.title, c.conent, c.article_id, c.create_time, c.is_show,c.article_id")
            ->where($map)
            ->order("$order $order1")
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
//        echo $list;die;
        $res['show'] = $show;
        $res['list'] = $list;
        return $res;
    }

    //更改评论是否显示
    public function updateShow($id,$is_show)
    {
        $this->where("id=$id")->save(array('is_show'=>$is_show));
    }

    public function queryComInfoById($id)
    {
        $info = $this
            ->field("conent")
            ->where("id=$id")
            ->find();
        return $info;
    }

    public function deleteCom($id)
    {
        $this->where("id=$id")->delete();
    }

    //根据文章id查询评论数
    public function queryTotalComment($id)
    {
        return $this->field("count(id) total")->where("article_id=$id")->find();
    }
}